package com.qing.springbootorderservice.dao;

import com.qing.springbootorderservice.pojo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(rollbackFor = Exception.class)
public class OrderDataBaseService {


	@Autowired
	private JdbcTemplate jdbcTemplate;

	/**
	 * 保存订单记录
	 * @param order
	 */
	public void saveOrder(Order order) throws Exception {
		//定义保存SQL
		//1：添加订单记录order
		String sqlString="INSERT INTO `dispatcher`.`dispatcher_order` (`order_id`, `status`, `order_content`, `unique_id`) VALUES (?, ?, ?, ?)";
		int count=jdbcTemplate.update(sqlString,order.getOrderId(),order.getStatus(),order.getOrderContent(),order.getUniqueId());
		if(count!=1){
			throw new Exception("订单创建失败，原因【数据库操作失败哦】");
		}
		//因为在下课可能会rabbit出现宕机，就引发消息是没有放入MQ，为消息可靠生产，对消息做一次冗余
		saveLocalMessage(order);
	}

	//保存信息到本地
	public void saveLocalMessage(Order order) throws Exception {
		//添加记录 order_message
		String sqlString="INSERT INTO `dispatcher`.`dispatcher_order_message` (`order_id`, `status`, `order_content`, `unique_id`) VALUES (?, ?, ?, ?)";
		int count=jdbcTemplate.update(sqlString,order.getOrderId(),order.getStatus(),order.getOrderContent(),order.getUniqueId());
		if(count!=1){
			throw  new Exception("出现异常，原因【操作数据库失败】");
		}
	}
}
